#include"Sock.hpp"
#include<unistd.h>
void ServiceIO(int sock)
{
  while(1)
  {
     //读取客户端发送的内容，然后把内容重新响应回去 
     char buf[1024] = {0};
     ssize_t n = read(sock,buf,sizeof(buf)-1);
     if(n > 0)
     {
      buf[n] = 0;
      cout <<"client #" << buf << endl;
      std::string echo = ">>>>>>>server<<<<<";
      echo += buf;
      write(sock,echo.c_str(),echo.size());
     }
     else if(n == 0)
     {
       cout << "client quit...." << endl;
       break;
     }
     else 
     {
       cerr << "read error" << endl;
       break;
     }
  } 
}
void Usage(std::string proc)
{
  cout << "Usage\n\t" << proc <<" tcp_port" << endl;
  exit(1);
}
int main(int argc,char* argv[])
{
  if(argc != 2)
  {
    Usage(argv[0]);
  }
  uint16_t port = atoi(argv[1]);
  int listen_sock = Sock::Socket();
  Sock::Bind(listen_sock,port);
  Sock::Listen(listen_sock);
  for(;;)
  {
    int new_sock = Sock::Accept(listen_sock);
    if(new_sock < 0)
    {
      continue;
    }
    ServiceIO(new_sock);
    close(new_sock);
  }
  return 0;
}
